package com.lsh.oms.provider.service.payment;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.model.CommonResult;
import com.lsh.base.common.utils.CollectionUtils;
import com.lsh.oms.api.model.payment.OrderOnlinePayRequestDTO;
import com.lsh.oms.api.model.payment.PayItem;
import com.lsh.oms.api.service.payment.IOrderPaymentOnlineRestService;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.*;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.exception.ExceptionStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.payment.BillPaymentInfo;
import com.lsh.oms.core.proxy.handler.OrderConcurrentHandler;
import com.lsh.oms.core.proxy.service.PaymentProxy;
import com.lsh.oms.core.service.order.OrderUpdateService;
import com.lsh.oms.core.service.payment.BillPaymentService;
import com.lsh.oms.core.service.payment.PaymentService;
import com.lsh.oms.core.utils.DateUtil;
import com.lsh.oms.core.utils.IdGenerator;
import com.lsh.oms.provider.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.*;

/**
 * Project Name: OrderPaymentOnlineRestService
 * 北京链商电子商务有限公司
 *
 * @author wangliutao
 * Date: 18/5/29
 * Package Name: com.lsh.oms.provider.service.payment
 * Description:
 */
@Service(protocol = "rest", timeout = 30000)
@Path("order/pay")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_FORM_URLENCODED})
@Produces({ContentType.APPLICATION_JSON_UTF_8,MediaType.APPLICATION_FORM_URLENCODED})
public class OrderPayRestServiceImpl extends BaseService implements IOrderPaymentOnlineRestService,InitializingBean{

    private static final Logger logger = LoggerFactory.getLogger(OrderPayRestServiceImpl.class);

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private BillPaymentService billPaymentService;

    @Autowired
    private PaymentProxy paymentProxy;

    @Autowired
    private OrderUpdateService orderUpdateService;

    Map<String,String> payChannelConf;


    @POST
    @Path("prepay")
    @Override
    public CommonResult<JSONObject> orderPay(OrderOnlinePayRequestDTO payRequest) {
        logger.info("[在线支付] payRequest -> {}", JSON.toJSONString(payRequest));
        CommonResult<JSONObject> commonResult = new CommonResult<>();

        try {
            Long venderId = this.getVenderId();
            payRequest.setVenderId(venderId);
            // 校验参数
            this.validationParams(payRequest);

            if (payRequest.getPayItems() == null || payRequest.getPayItems().size() != 1) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "payItems 下单数据有误");
            }
            PayItem payItem = payRequest.getPayItems().get(0);

            // 订单支付加锁,防止重复支付
            if (!OrderConcurrentHandler.lockOrder(payItem.getOrderCode())) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单正在处理中……");
            }

            // 订单超时mark, 防止数据边界异常(即用户在订单超时的最后一秒支付, 在等待payment系统异步回调中, 定时任务触发取消订单)
            if (!this.paymentService.lock(payItem.getOrderCode())) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单加锁失败……");
            }

            List<OrderHead> orderHeads = paymentService.getOrderHeadsByOrderCodes(Collections.singletonList(payItem.getOrderCode()));

            if (orderHeads == null || orderHeads.size() != 1) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "关联订单有误");
            }

            OrderHead head = orderHeads.get(0);

            if(!head.getVenderId().equals(venderId)){
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "租户信息不统一");
            }

            BigDecimal orderAmount = payItem.getOrderAmount();
            if (null == orderAmount) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "payItem orderAmount is null");
            }

            if (payRequest.getPayChannel().equals(PayChannel.BALANCE_PAYMENT.getCode())) {
                commonResult = this.orderBalancePay(payRequest, head, payItem);
            } else {
                commonResult = this.orderGatewayPay(payRequest, head, payItem);
            }
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("[在线支付] 业务异常code : " + e.getCode() + ", 异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ReturnCode.SYS_ERROR);
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("[在线支付] 异常code : " + ExceptionStatus.E3001001.getCode() + ",异常信息: " + e.getMessage(), e);
        } finally {
            try {
                for (PayItem payItem : payRequest.getPayItems()) {
                    OrderConcurrentHandler.unlockOrder(payItem.getOrderCode());
                }
            } catch (Exception e) {
                logger.error("[在线支付] redis操作异常", e);
            }
        }

        return commonResult;
    }

    /**
     * @param payRequest
     * @param head
     * @param payItem
     * @return
     */
    public CommonResult<JSONObject> orderGatewayPay(OrderOnlinePayRequestDTO payRequest, OrderHead head, PayItem payItem) {
        logger.info("[在线支付] payRequest -> {}", JSON.toJSONString(payRequest));
        CommonResult<JSONObject> commonResult = new CommonResult<>();

        try {
            // 校验orderHead状态
            BillPaymentInfo billPaymentInfo = this.validationGateway(head);
            BigDecimal orderMoney = head.getExpectPayAmount().add(head.getFreight());
            //金额检查
            if (null != billPaymentInfo) {
                if ((billPaymentInfo.getPayAmount().add(payItem.getOrderAmount())).compareTo(orderMoney) != 0) {
                    throw new BusinessException(ReturnCode.REQUEST_FAIL, "plus 订单支付金额与请求金额不一致");
                }
            } else if ((payItem.getOrderAmount().compareTo(orderMoney) != 0)) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "only 订单支付金额与请求金额不一致");
            }

            //插入请求记录
            BillPaymentInfo billPaymentInfo4db = this.init(payRequest);
            billPaymentInfo4db.setVenderId(head.getVenderId());
            int flag = billPaymentService.addOrUpdateOne(billPaymentInfo4db);
            if (flag <= 0) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "添加支付流水失败");
            }

            OrderHead orderHead = new OrderHead();
            Long orderCode = payItem.getOrderCode();
            orderHead.setOrderCode(orderCode);
            orderHead.setPayChannel(Integer.valueOf(payRequest.getPayChannel()));
            paymentService.updatePayStatus(orderHead, false);
            logger.info("[在线支付] 更新db, orderHead : {}", JSON.toJSONString(orderHead));

            JSONObject content = paymentProxy.prePay(billPaymentInfo4db);
            if (content == null) {
                logger.info("[在线支付] [request payment fail ] {}", JSON.toJSONString(content));
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求支付失败");
            }

            commonResult.setCode(ReturnCode.REQUEST_SUCCESS);
            commonResult.setData(content);
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("[在线支付] 业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ReturnCode.SYS_ERROR);
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("[在线支付] 异常code : " + ExceptionStatus.E3001001.getCode() + ",异常信息: " + e.getMessage(), e);
        }

        return commonResult;
    }

    /**
     * @param payRequest
     * @param head
     * @param payItem
     * @return
     */
    public CommonResult<JSONObject> orderBalancePay(OrderOnlinePayRequestDTO payRequest, OrderHead head, PayItem payItem) {
        logger.info("[在线支付] payRequest -> {}", JSON.toJSONString(payRequest));
        CommonResult<JSONObject> commonResult = new CommonResult<>();
        try {
            // 校验orderHead状态
            this.validationBalance(head, payRequest.getPayChannel());
            BigDecimal orderMoney = head.getExpectPayAmount().add(head.getFreight());

            if ((orderMoney.compareTo(payItem.getOrderAmount()) < 0)) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单支付金额与请求金额不一致");
            }

            //插入请求记录
            BillPaymentInfo billPaymentInfo4db = this.init(payRequest);
            // TODO 2019-09-08 -venderId
            billPaymentInfo4db.setVenderId(head.getVenderId());
            int flag = billPaymentService.addOrUpdateOne(billPaymentInfo4db);
            if (flag <= 0) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "更新支付记录失败");
            }

            JSONObject content = paymentProxy.prePay(billPaymentInfo4db);
            if (content == null) {
                logger.info("[在线支付] [request payment fail ] ");
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求支付失败");
            }
            String paymentNo = this.getPaymentNo(content);
            if (StringUtils.isNotBlank(paymentNo)) {
                // 余额支付 支付成功
                BillPaymentInfo billPaymentInfo4update = new BillPaymentInfo();
                billPaymentInfo4update.setPayTradeId(billPaymentInfo4db.getPayTradeId());
                billPaymentInfo4update.setPaySequence(paymentNo);
                billPaymentInfo4update.setPayStatus(PayStatus.PAID.getValue());
                billPaymentInfo4update.setUpdateTime(new Date());
                billPaymentService.updateByPayTradeId(billPaymentInfo4update);
//              余额支付金额 都等于 订单应付金额
                if (orderMoney.compareTo(payItem.getOrderAmount()) == 0) {
                    OrderHead orderHead4update = paymentService.initOrderHead4update(payRequest.getPayChannel(), payItem.getOrderAmount(), paymentNo, head);
                    logger.info("[在线支付--回调] update db [start], orderHead: {}", JSON.toJSONString(orderHead4update));
                    boolean addTaskFlag = true;
                    if (OrderStatus.ORDER_NO_EDIT.getIndex() == orderHead4update.getOrderStatus()) {
                        addTaskFlag = false;
                    }

                    this.orderUpdateService.updateOrderHead(head.getOrderCode(), orderHead4update, addTaskFlag,head.getVenderId());
                }

                OrderHead orderHead4update = new OrderHead();
                //钱包支付金额
                orderHead4update.setPayReliefAmout(payItem.getOrderAmount());
                orderHead4update.setUpdateTime(DateUtil.getCurrentTime());
                this.orderUpdateService.updateOrderHead(head.getOrderCode(), orderHead4update);
            }
            commonResult.setCode(ReturnCode.REQUEST_SUCCESS);
            commonResult.setData(content);
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("[在线支付] 业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ReturnCode.SYS_ERROR);
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("[在线支付] 异常code : " + ExceptionStatus.E3001001.getCode() + ",异常信息: " + e.getMessage(), e);
        }

        return commonResult;
    }

    /**
     * @param misPayResponseContent
     * @return
     */
    private String getPaymentNo(JSONObject misPayResponseContent) {
        String outTradeNo = null;
        if (misPayResponseContent == null) {
            return outTradeNo;
        }
        misPayResponseContent.getString("trade_id");

        String misPurseResponse = misPayResponseContent.getString("misPurseResponse");

        if (StringUtils.isBlank(misPurseResponse)) {
            return outTradeNo;
        }

        JSONObject purseResponse = JSON.parseObject(misPurseResponse);
        String code = purseResponse.getString("code");
        if (code.equals("1")) {
            outTradeNo = purseResponse.getString("out_trade_no");
        }

        return outTradeNo;
    }

    /**
     * @param payRequestDTO
     * @return
     */
    private BillPaymentInfo init(OrderOnlinePayRequestDTO payRequestDTO) {
        PayItem payItem = payRequestDTO.getPayItems().get(0);
        List<OrderHead> orderHeads = paymentService.getOrderHeadsByOrderCodes(Collections.singletonList(payItem.getOrderCode()));

        if (orderHeads == null || orderHeads.size() != 1) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "关联订单有误");
        }
        OrderHead head = orderHeads.get(0);
        //插入请求记录
        BillPaymentInfo billPaymentInfo4db = billPaymentService.selectOne(head.getOrderCode(), Integer.valueOf(payRequestDTO.getPayChannel()));
        if (null != billPaymentInfo4db) {

            if (billPaymentInfo4db.getPayStatus().equals(PayStatus.PAID.getValue())) {
                throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单支付状态:已支付, 订单号: ");
            }
        } else {
            billPaymentInfo4db = new BillPaymentInfo();

            billPaymentInfo4db.setCreateTime(new Date());
            billPaymentInfo4db.setPayTradeId(IdGenerator.genId() + "");
            billPaymentInfo4db.setBillCode(payItem.getOrderCode());
            billPaymentInfo4db.setPayChannelType(Integer.valueOf(payRequestDTO.getPayChannel()));

            billPaymentInfo4db.setVenderId(payRequestDTO.getVenderId());
        }
        billPaymentInfo4db.setUpdateTime(new Date());
        billPaymentInfo4db.setPayWay(payRequestDTO.getPaySource());
        billPaymentInfo4db.setReturnUrl(payRequestDTO.getReturnUrl());
        billPaymentInfo4db.setPayTime(new Date());
        billPaymentInfo4db.setPayStatus(PayStatus.NOT_PAID.getValue());
        billPaymentInfo4db.setPayAmount(payItem.getOrderAmount());
        billPaymentInfo4db.setOpenId(payRequestDTO.getOpenId());
        billPaymentInfo4db.setUid(payRequestDTO.getUid());

        JSONObject ext = new JSONObject();
        Integer system = payRequestDTO.getSystem();
        Integer systemChannel = payRequestDTO.getSystemChannel();
        if(system == null){
            system = 1;
        }
        if (systemChannel == null) {
            systemChannel = 1;
        }
        ext.put("system",system);
        ext.put("systemChannel",systemChannel);

        billPaymentInfo4db.setExt(ext.toJSONString());

        return billPaymentInfo4db;
    }


    /**
     * 支付查询接口  调用频率比较低
     *
     * @param codes
     * @return
     */
    @POST
    @Path("query")
    @Override
    public CommonResult<JSONObject> orderPayQuery(String codes) {
        logger.info("[在线支付--查询] param --> {}", codes);
        CommonResult<JSONObject> commonResult = new CommonResult<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(codes);
            List<Long> orderCodes = JSON.parseArray(jsonObject.getString("orderCodes"), Long.class);
            if (CollectionUtils.isEmpty(orderCodes)) {
                commonResult.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
                commonResult.setMessage("request params is null!");
                return commonResult;
            }

            List<OrderHead> orderHeads = paymentService.getOrderHeadsByOrderCodes(orderCodes);

            if (orderHeads == null || orderHeads.size() != 1) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "关联订单不存在");
            }

            OrderHead head = orderHeads.get(0);

            if (head.getPayType().intValue() == PayType.PAY_ON_DELIVERY.getValue().intValue()) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单支付类型:货到付款, 订单号: " + head.getOrderCode());
            }

            JSONObject content = new JSONObject();
            content.put(head.getOrderCode().toString(), this.getPayStatus(head).getValue() + "");

            commonResult.setCode(ReturnCode.REQUEST_SUCCESS);
            commonResult.setMessage("success");
            commonResult.setData(content);
            return commonResult;
        } catch (Exception e) {
            logger.error("[在线支付--查询] error: " + e.getMessage(), e);
            commonResult.setCode(ReturnCode.SYS_ERROR);
            commonResult.setMessage(e.getMessage());
            return commonResult;
        }
    }


    private PayStatus getPayStatus(OrderHead head) {
        PayStatus payStatus = PayStatus.PAID;
        if (!head.getPayStatus().equals(PayStatus.PAID.getValue()) && head.getPayChannel() != 0) {
            // TODO 支付记录 后期优化
//            JSONObject resp = paymentProxy.query(head.getOrderCode().toString(), null);
//            logger.info("[在线支付--查询] [request payment] {}", resp.toJSONString());
//            if (resp == null) {
//                throw new BusinessException(ReturnCode.REQUEST_FAIL, "查询支付系统失败");
//            }
            // 3支付成功，2支付中，4支付失败
//            Integer payCode = resp.getInteger("pay_code");
//            if (payCode == 2) {
//                payStatus = PayStatus.NOT_PAID;
//            } else if (payCode == 3) {
//                payStatus = PayStatus.PAID;
//                //修改订单支付结果
//                this.updatePayStatus(head);
//            } else {
//                payStatus = PayStatus.PAID_FAILED;
//            }

            payStatus = PayStatus.NOT_PAID;
        }

        return payStatus;
    }

    /**
     * 修改订单支付结果
     *
     * @param orderHead
     */
    private void updatePayStatus(OrderHead orderHead) {
        OrderHead headUpdate = new OrderHead();
        headUpdate.setPayStatus(PayStatus.PAID.getValue());
        headUpdate.setOrderCode(orderHead.getOrderCode());

        paymentService.updatePayStatus(headUpdate, false);
    }

    /**
     * 支付请求校验
     *
     * @param payRequest
     */
    private void validationParams(OrderOnlinePayRequestDTO payRequest) {
        if (payRequest == null) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求参数为空,请检查");
        }

        if (org.springframework.util.CollectionUtils.isEmpty(payRequest.getPayItems())) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求参数[orderCodes]为空,请检查");
        }
        if (payRequest.getVenderId() == null) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "VenderId 请求参数为空,请检查");
        }

        if (StringUtils.isBlank(payRequest.getPayChannel())) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求参数[payChannel]为空,请检查");
        }
        String payChannel = payRequest.getPayChannel();
        if (!(PayChannel.getAllPayCodes().contains(payChannel))) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求参数[payChannel]不正确,请检查");
        }

        //微信支付,如果是h5,需要判断openId是否存在
        if (PayChannel.WX.getCode().equals(payChannel)) {
            if (Integer.valueOf(payRequest.getPaySource()).intValue() == PayWay.H5.getCode() && StringUtils.isBlank(payRequest.getOpenId())) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "微信支付(h5),请求参数[openId]不能为空,请检查");
            }
        }

        if (payChannel.equals(PayChannel.ON_CREDIT.getCode()) || payChannel.equals(PayChannel.PRE_PAYMENT.getCode()) || payChannel.equals(PayChannel.BALANCE_PAYMENT.getCode())) {
            if (StringUtils.isBlank(payRequest.getUid())) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "钱包支付,请求参数[uid]不能为空,请检查");
            }
        }

        if (payChannel.equals(PayChannel.ALI.getCode()) && payChannel.equals(PayChannel.WX.getCode())) {
            if (StringUtils.isEmpty(payRequest.getReturnUrl()) || !payRequest.getReturnUrl().startsWith("http")) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求参数[returnUrl]为空或者格式不正确,请检查");
            }
        }

    }

    /**
     * 余额支付校验
     *
     * @param head
     * @param payChannel
     */
    private void validationBalance(OrderHead head, String payChannel) {
        Long orderCode = head.getOrderCode();
        if (head.getOrderStatus().intValue() > OrderStatus.ORDER_NEW.getIndex()) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单状态不正确, 订单状态:" + OrderStatus.getName(head.getOrderStatus()) + " 订单号: " + orderCode);
        }
        // 判断订单的支付类型,是否是在线支付
        if (head.getPayType().intValue() == PayType.PAY_ON_DELIVERY.getValue().intValue()) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单支付类型:货到付款, 订单号: " + orderCode);
        }

        if (head.getPayStatus().intValue() == PayStatus.PAID.getValue().intValue()) {
            throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单支付状态:已支付, 订单号: " + orderCode);
        }

        List<BillPaymentInfo> billPaymentInfoList$success = this.getSuccessBillInfo(head);

        if (!org.springframework.util.CollectionUtils.isEmpty(billPaymentInfoList$success)) {
            throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单已支付 不能余额支付: " + orderCode);
        }

    }

    /**
     * 订单状态校验
     *
     * @param head
     * @return
     */
    private BillPaymentInfo validationGateway(OrderHead head) {
        Long orderCode = head.getOrderCode();
        if (head.getOrderStatus().intValue() > OrderStatus.ORDER_NEW.getIndex()) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单状态不正确, 订单状态:" + OrderStatus.getName(head.getOrderStatus()) + " 订单号: " + orderCode);
        }
        // 判断订单的支付类型,是否是在线支付
        if (head.getPayType().intValue() == PayType.PAY_ON_DELIVERY.getValue().intValue()) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单支付类型:货到付款, 订单号: " + orderCode);
        }

        if (head.getPayStatus().intValue() == PayStatus.PAID.getValue().intValue()) {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单支付状态:已支付, 订单号: " + orderCode);
        }

        List<BillPaymentInfo> billPaymentInfoList$success = this.getSuccessBillInfo(head);

        if (!org.springframework.util.CollectionUtils.isEmpty(billPaymentInfoList$success)) {
            //存在支付成功的记录 切是多个
            if (billPaymentInfoList$success.size() != 1) {
                throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单已支付: " + orderCode);
            }
            BillPaymentInfo billPaymentInfo = billPaymentInfoList$success.get(0);

            //存在支付成功的记录 只有一个 但是支付类型不余额支付
            if (!String.valueOf(billPaymentInfo.getPayChannelType()).equals(PayChannel.BALANCE_PAYMENT.getCode())) {
                throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单已支付: " + orderCode);
            }
            BigDecimal orderMoney = head.getExpectPayAmount().add(head.getFreight());
            //存在支付成功的记录 只有一个切是余额支付 请求金额等于订单应付金额
            if (billPaymentInfo.getPayAmount().compareTo(orderMoney) >= 0) {
                throw new BusinessException(ReturnCode.REQUEST_SUCCESS_DU, "订单支付已支付: " + orderCode);
            }

            return billPaymentInfo;
        }

        return null;
    }

    /**
     * 获取成功的支付记录
     *
     * @param head
     * @return
     */
    private List<BillPaymentInfo> getSuccessBillInfo(OrderHead head) {
        List<BillPaymentInfo> billPaymentInfos = billPaymentService.selectList(head.getOrderCode());
        List<BillPaymentInfo> billPaymentInfoList$success = new ArrayList<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(billPaymentInfos)) {
            for (BillPaymentInfo billPaymentInfo : billPaymentInfos) {
                Integer paystatus = billPaymentInfo.getPayStatus();
                if (paystatus.equals(PayStatus.PAID.getValue())) {
                    billPaymentInfoList$success.add(billPaymentInfo);
                }
            }
        }

        return billPaymentInfoList$success;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        payChannelConf = PayChannel.payConf();
    }


    /**
     * 支付查询接口  调用频率比较低
     *
     * @return
     */
    @GET
    @Path("getPayChannel")
    @Override
    public CommonResult<Map<String,String>> getPayChannel() {
        CommonResult<Map<String,String>> commonResult = new CommonResult<>();
        try {

            commonResult.setCode(ReturnCode.REQUEST_SUCCESS);
            commonResult.setMessage("success");
            commonResult.setData(payChannelConf);
            return commonResult;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            commonResult.setCode(ReturnCode.SYS_ERROR);
            commonResult.setMessage(e.getMessage());
            return commonResult;
        }
    }
}
